<template>
  <div class="products-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>商品管理</span>
          <div class="header-actions">
            <el-input
              v-model="searchQuery"
              placeholder="搜索商品..."
              style="width: 200px; margin-right: 16px"
              clearable
            />
            <el-button type="primary" @click="handleAdd">添加商品</el-button>
          </div>
        </div>
      </template>

      <el-table :data="filteredProducts" style="width: 100%">
        <el-table-column prop="productId" label="ID" width="80" align="center" />
        <el-table-column prop="name" label="商品名称" width="200" align="center" />
        <el-table-column prop="category" label="分类" width="120" align="center" />
        <el-table-column prop="price" label="价格" width="100" align="center">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100" align="center" />
        <el-table-column prop="sales" label="销售数量" width="100" align="center" />
        <el-table-column label="评分" width="150" align="center">
          <template #default="scope">
            <el-rate
              v-model="scope.row.rating"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 商品表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加商品' : '编辑商品'"
      width="600px"
      destroy-on-close
    >
      <el-form
        ref="productFormRef"
        :model="productForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="productForm.category">
            <el-option label="运动器材" value="运动器材" />
            <el-option label="营养补剂" value="营养补剂" />
            <el-option label="养生书籍" value="养生书籍" />
            <el-option label="健康装备" value="健康装备" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="productForm.price" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="productForm.stock" :min="0" />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="productForm.description"
            type="textarea"
            rows="3"
          />
        </el-form-item>
        <el-form-item label="商品图片" prop="imageUrls">
          <el-input v-model="productForm.imageUrls" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getProductList, addProduct, updateProduct, deleteProduct } from '@/api/admin/product'

export default {
  name: 'ProductsManagement',
  setup() {
    const searchQuery = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const products = ref([])
    const loading = ref(false)
    const dialogVisible = ref(false)
    const dialogType = ref('add')
    const productFormRef = ref(null)
    const productForm = ref({
      productId: '',
      name: '',
      category: '',
      price: 0,
      stock: 0,
      description: '',
      imageUrls: ''
    })

    // 获取商品列表
    const fetchProducts = async () => {
      loading.value = true
      try {
        const res = await getProductList({
          page: currentPage.value,
          pageSize: pageSize.value
        })
        if (res && Array.isArray(res)) {
          products.value = res
          total.value = res.length
        }
      } catch (error) {
        console.error('获取商品列表失败:', error)
        ElMessage.error('获取商品列表失败')
      } finally {
        loading.value = false
      }
    }

    const filteredProducts = computed(() => {
      return products.value.filter(item => 
        item.name.includes(searchQuery.value) ||
        item.category.includes(searchQuery.value)
      )
    })

    const handleAdd = () => {
      dialogType.value = 'add'
      productForm.value = {
        productId: '',
        name: '',
        category: '',
        price: 0,
        stock: 0,
        description: '',
        imageUrls: ''
      }
      dialogVisible.value = true
    }

    const handleEdit = (row) => {
      dialogType.value = 'edit'
      productForm.value = { ...row }
      dialogVisible.value = true
    }

    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
          type: 'warning'
        })
        await deleteProduct(row.productId)
        ElMessage.success('删除成功')
        fetchProducts()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除商品失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }

    const handleSubmit = async () => {
      productFormRef.value?.validate(async (valid) => {
        if (valid) {
          try {
            const submitData = { ...productForm.value }
            if (dialogType.value === 'add') {
              delete submitData.productId
              const response = await addProduct(submitData)
              if (response || response === true) {
                ElMessage.success('添加成功')
                dialogVisible.value = false
                fetchProducts()
              }
            } else {
              const response = await updateProduct(submitData)
              if (response || response === true) {
                ElMessage.success('修改成功')
                dialogVisible.value = false
                fetchProducts()
              }
            }
          } catch (error) {
            console.error('操作失败:', error)
            ElMessage.error(error.response?.data?.message || '操作失败')
          }
        }
      })
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      fetchProducts()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchProducts()
    }

    onMounted(() => {
      fetchProducts()
    })

    return {
      searchQuery,
      currentPage,
      pageSize,
      total,
      filteredProducts,
      handleAdd,
      handleEdit,
      handleDelete,
      handleSizeChange,
      handleCurrentChange,
      loading,
      dialogVisible,
      dialogType,
      productForm,
      productFormRef,
      handleSubmit
    }
  }
}
</script>

<style scoped>
.products-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>